package com.wuliang.generate.response.author.configs;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 用户认证
 * @author WuLiang
 */
@Slf4j
@Component
public class SecurityAuthenticationProvider implements AuthenticationProvider {

    /**
     * 密码工具
     */
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 此处主要用于对用户进行权限认证
     *
     * @param authentication 用户详情
     * @return 权限
     * @throws AuthenticationException 会认证失败
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
//        获取用户详情
        User detail = (User) authentication.getDetails();

        log.info(detail.getUsername() + " will login by the password " + authentication.getCredentials());
//        比较前台的密码是否与数据库中的密码一致
        if (bCryptPasswordEncoder.matches(authentication.getCredentials().toString(), detail.getPassword())) {
//            返回一个已认证的用户信息
            return new UsernamePasswordAuthenticationToken(detail.getUsername(), detail.getPassword(),
                                                           detail.getAuthorities());
        } else {
//            认证失败
            return new UsernamePasswordAuthenticationToken(detail.getUsername(), detail.getPassword());
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}
